package com.demo.phonerepair.controller;

import com.demo.phonerepair.module.LoginUser;
import com.demo.phonerepair.module.PartsQueryModule;
import com.demo.phonerepair.module.RegisterUser;
import com.demo.phonerepair.pojo.User;
import com.demo.phonerepair.service.UserService;
import com.demo.phonerepair.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //接收参数
    @PostMapping("/login")
    public Result<LoginUser> login(@RequestParam(value = "usernameOrEmail") String usernameOrEmail, @RequestParam(value = "password") String password) {
        userService.login(usernameOrEmail, password);
        LoginUser loginUser = userService.login(usernameOrEmail, password);
        if (loginUser == null)
            return Result.fail("用户名或密码错误", 400);
        return Result.success(loginUser);
    }

    // 修复请求方法为 POST，并且正确使用传入的参数
    @PostMapping("/createUser")
    public Result<String> register(@RequestBody RegisterUser registerUser) {
        return userService.register(registerUser);
    }

    @GetMapping("/getAllUsers")
    public Result<Map<String, Object>> getAlluser(PartsQueryModule partsQueryModule) {
        int userId = partsQueryModule.getUserId();

        String searchKeyword = partsQueryModule.getSearchKeyword();
        Integer pageNum = partsQueryModule.getPageNum();
        Integer pageSize = partsQueryModule.getPageSize();
        String sortField = partsQueryModule.getSortField();
        String sortOrder = partsQueryModule.getSortOrder();
        return userService.getAllUser(userId, searchKeyword, pageNum, pageSize, sortField, sortOrder);
    }

    @PostMapping("updateUser")
    public Result<String> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @DeleteMapping("/delete/{userId}")
    public Result<String> deleteUser(@PathVariable("userId") Integer userId) {
        int result = userService.deleteUserByUserId(userId);
        if (result > 0) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败，配件不存在", 404);
        }

    }
}
